class MyPageHeader extends BaseEditMaster {
    constructor(dataId, currentTaskPrivileges, nextTaskPrivileges, pageStatus, pageListData,
            returnUrl, fetchDataUrl, saveUrl, exportUrl, printUrl) {
        super(dataId, currentTaskPrivileges, nextTaskPrivileges, pageStatus, pageListData,
                returnUrl, fetchDataUrl, saveUrl, exportUrl, printUrl);
        this.hasFilterValue = true;
        this.checkUrl = "/inventory/stock_in/header/check.html";
        this.uncheckUrl = "/inventory/stock_in/header/uncheck.html";
    }
    GetFilterValue() {
        let item = {};
        item['HeaderId'] = parseInt(this.dataId);
        item['CurrentUserId'] = parseInt($("#UserId").val());
        item['WorkFlowId'] = $("#WorkFlowId").val() === '' ? 0 : parseInt($("#WorkFlowId").val());
        item['PageIndex'] = 1;
        item['Flag'] = 1;    // 表示要读取包括调达表等其他信息
        item['LimitPoLines'] = parseInt($("#page-size_02").val());
        item['Limit'] = parseInt($("#page-size_03").val());

        return item;
    }
    // 得到主表数据
    GetEntityData() {
        let item = {};
        item['headerId'] = $("#HeaderId").val();
        item['billNo'] = $.trim($("#BillNo").val());                                    // 入库单号（自动生成）
        item['wayBillNo'] = formatNullInputValue($.trim($("#WayBillNo").val()));        // 货单号
        item['arrivalDate'] = $.trim($("#ArrivalDate").val());                          // 到货日期
        item['stockInDate'] = $.trim($("#StockInDate").val());                          // 入库日期
        item['reasonId'] = $.trim($("#ReasonId").val());                                // 入库类型       
        item['supplierId'] = $.trim($("#SupplierId").val());                            // 供应商
        item['inspectedBy'] = formatNullInputValue($.trim($("#InspectedBy").val()));    // 验货人
        item['inspectedDate'] = $.trim($("#InspectedDate").val());                      // 验货日期
        item['description'] = formatNullInputValue($.trim($("#Description").val()));    // 备注
        item['createdBy'] = $.trim($("#UserId").val());
        item['updatedBy'] = $.trim($("#UserId").val());
        return JSON.stringify(item);
    }
    FillData(data) {
        let item = data.HeaderEntity;
        $("#HeaderId").val(item.headerId);
        $("#BillNo").val(item.billNo);
        $("#WayBillNo").val(item.wayBillNo);
        $("#ArrivalDate").val(item.arrivalDate);
        $("#StockInDate").val(item.stockInDate);
        $("#InspectedBy").val(item.inspectedBy);
        $("#InspectedByName").val(item.inspectedByName);
        $("#InspectedDate").val(item.inspectedDate);
        $("#SupplierId").val(formatNullData(item.supplierId));
        $("#SupplierName").val(formatNullData(item.supplierName));
        $("#ReasonId").val(formatNullData(item.reasonId));
        $("#BalanceFlag").val(formatNullData(item.balanceFlag));
        $("#UpdatedDate").val(formatNullData(item.updatedDate));
        $("#UpdatedBy").val(formatNullData(item.updatedBy));
        $("#UpdatedByName").val(formatNullData(item.updatedByName));
        $("#Description").val(item.description);
        $("#UpdatedBy").val(item.updatedBy);
        $("#UpdatedByName").val(item.updatedByName);
        $("#UpdatedDate").val(item.updatedDate);

        // 最后的审核人、审核日期
        $("#CheckedBy").val(item.checkedBy);
        $("#CheckedByName").val(item.checkedByName);
        $("#CheckedDate").val(item.checkedDate === null ? '' : item.checkedDate);
        $("#CheckedStatus").val(item.checkedStatus);
        $('#FlowOrderNo').val(item.flowOrderNo);
        
        // 设置用于控制的用户ID
        this.privateUserId = item.updatedBy;

        // 引入的订单列表
        _InstancePageLinesPoHeader.BuildDataTable(data.LinesPoHeaderList);
        // 引入的订单明细列表           
        _InstancePageLinesPoLines.BuildDataTable(data.LinesPoLinesList);
        // 入库单明细表             
        _InstancePageLines.BuildDataTable(data.LinesList);

        this.currentTaskPrivileges = item.currentTaskPrivileges;
        this.nextTaskPrivileges = item.nextTaskPrivileges;
        this.unCheckFlag = item.unCheckFlag;

        this.SetPageElementStatus(this.HidePageElement, this.ShowPageElement, function () {
        });
        
        // 编辑状态时不允许更改供应商
        $("#SupplierName").css({"cursor": "default"});
        $("#ChoiceSupplier").removeAttr("onclick");
        $("#BillNo").focus();
    }
    Save() {
        super.Save(function (data, _this) {
            if (data > 0) {
                if (parseInt(_this.pageStatus) === 1) {
                    $("#HeaderId").val(data);   // 设置刚才插入的记录ID
                    _this.dataId = data;
                    $("#Action").val(2);
                    _this.pageStatus = 2;
                    $("#menu_02").show();
                    $("#menu_03").show();
                }
            }
        });
    }
    New() {
        super.New();
        $("#HeaderId").val(0);
        this.FetchNewBillNo();   // 设置新的单据号

        // 默认设置一些值
        $("#UpdatedBy").val($("#UserId").val());
        $("#UpdatedByName").val($("#UserName").val());
        $("#UpdatedDate").val(getCurrentDate());
        $("#StockInDate").val(getCurrentDate());

        $("#menu_02").hide();
        $("#menu_03").hide();

        // 清空明细内容
        $("#tabPoListData tbody").empty();
        $("#tabData21 tbody").empty();
        $("#tabData22 tbody").empty();
        $("#tabData31 tbody").empty();
        $("#tabData32 tbody").empty();

        // 设置按钮可见
        $("#ButSaveLines").show();
        $("#ButExportToExcel1").hide();

        $("abbr.page_indicator_block,#wrapper__navbar_02").attr("_msh_page", 1);
        $("abbr.page_indicator_block,#wrapper__navbar_03").attr("_msh_page", 1);

        $("#BillNo").focus();
    }
    // 自动设置设置新的单据号
    FetchNewBillNo() {
        super.DoAjax({}, "/inventory/stock_in/header/fetchNewNoOfBill.html", function (data, _this) {
            $("#BillNo").val(data.BillNo);
        });
    }
    DoChoiceSupplier() {
        let _choice = new CommonChoice();
        let params = {};
        params['Flag'] = 0;
        params['CurrentUserId'] = null;
        params['NotInGroupId'] = null;
        _choice.DoChoiceSupplier(params, '选择供应商', (data) => {
            if (data) {
                // 判断是否数据发生了改变如果改变则设置改变标记
                if ($("#SupplierName").val() !== data[1]) {
                    $("#form_data").data("changed", true);
                }
                $("#SupplierId").val(data[0]);
                $("#SupplierNo").val(data[4]);
                $("#SupplierName").val(data[1]);
                $("#Attn").val(data[2]);
                $("#Fax").val(data[3]);
                $("#SupplierName").focus();
            }
        });
        $("#SupplierName").focus();
    }
    DoChoiceInspectedBy() {
        let _choice = new CommonChoice();
        _choice.DoChoiceUser(0, '选择验料员', '采购', (data) => {
            if (data) {
                // 判断是否数据发生了改变如果改变则设置改变标记
                if ($("#InspectedByName").val() !== data[1]) {
                    $("#form_data").data("changed", true);
                }
                $("#InspectedBy").val(data[0]);
                $("#InspectedByName").val(data[1]);
                $("#InspectedByName").focus();
            }
        });
        $("#PurchasedByName").focus();
    }
    DoCheck() {
        let item = {};
        item['HeaderId'] = parseInt($("#HeaderId").val());
        item['WorkFlowId'] = parseInt($("#WorkFlowId").val());
        item['NodeOrder'] = parseInt($("#FlowOrderNo").val());
        item['CheckedBy'] = parseInt($("#UserId").val());
        item['IsCheckCurrentNode'] = this.currentTaskPrivileges === 0 ? 0 : 1;
        item['PageIndex'] = $("abbr.page_indicator_block,#wrapper__navbar_04").attr("_msh_page");
        item['Limit'] = parseInt($("#page-size_04").val());

        $.ajax({
            type: "POST",
            url: parent.basePath + this.checkUrl,
            timeout: 30 * 1000,
            data: JSON.stringify(item),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: () => {
            }
        }).done(data => {
            let item = data.HeaderEntity;
            // 最后的审核人、审核日期
            $("#CheckedBy").val(item.checkedBy);
            $("#CheckedByName").val(item.checkedByName);
            $("#CheckedDate").val(item.checkedDate === null ? '' : item.checkedDate);
            $("#CheckedStatus").val(item.checkedStatus);
            $('#FlowOrderNo').val(item.flowOrderNo);
            // 合同明细表             
            _InstancePageLines.BuildDataTable(data.PoLinesList);
            this.currentTaskPrivileges = item.currentTaskPrivileges;
            this.nextTaskPrivileges = item.nextTaskPrivileges;
            this.unCheckFlag = item.unCheckFlag;

            // 设置画面各个元素状态
            this.SetPageElementStatus(this.HidePageElement, this.ShowPageElement, function () {
            });
        }).fail(function (data) {
            ajaxError(data, 1);
        }).always(function ( ) {
        });
    }
    Uncheck() {
        let item = {};
        item['HeaderId'] = parseInt($("#HeaderId").val());
        item['WorkFlowId'] = parseInt($("#WorkFlowId").val());
        item['NodeOrder'] = parseInt($("#FlowOrderNo").val());
        item['CheckedBy'] = parseInt($("#UserId").val());
        item['PageIndex'] = $("abbr.page_indicator_block,#wrapper__navbar_04").attr("_msh_page");
        item['Limit'] = parseInt($("#page-size_04").val());

        $.ajax({
            type: "POST",
            url: parent.basePath + this.uncheckUrl,
            timeout: 30 * 1000,
            data: JSON.stringify(item),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: () => {
            }
        }).done(data => {
            let item = data.HeaderEntity;
            // 最后的审核人、审核日期
            $("#CheckedBy").val(item.checkedBy);
            $("#CheckedByName").val(item.checkedByName);
            $("#CheckedDate").val(item.checkedDate === null ? '' : item.checkedDate);
            $("#CheckedStatus").val(item.checkedStatus);
            $('#FlowOrderNo').val(item.flowOrderNo);
            // 合同明细表             
            _InstancePageLines.BuildDataTable(data.PoLinesList);

            this.currentTaskPrivileges = item.currentTaskPrivileges;
            this.nextTaskPrivileges = item.nextTaskPrivileges;
            this.unCheckFlag = item.unCheckFlag;

            // 设置画面各个元素状态
            this.SetPageElementStatus(this.HidePageElement, this.ShowPageElement, function () {
            });
        }).fail(data => {
            ajaxError(data, 1);
        }).always(( ) => {
        });
    }
    ShowPageElement() {
        $("Button.act__save").show();
        if (!$("span.act__delete").hasClass("act__delete")) {
            $("span.act__delete").addClass("trash");
            $("span.act__delete i").addClass("fa-all fa-trash-o fa-1");
        }
        $("#ButEditSurCharges").css("margin-left", "15px");
    }
    HidePageElement() {
        $("Button.act__save").hide();
        $("span.act__delete").removeClass("trash");
        $("span.act__delete i").removeClass("fa-all fa-trash-o fa-1");
        $("#ButEditSurCharges").css("margin-left", "0");
    }
}

class MyPageLinesPoHeader extends BaseEditSlave {
    constructor() {
        super('', '', '');
    }
    // 构建明细数据列表
    BuildDataTable(result) {
        $('#tabPoListData tbody').empty();
        if (result === null)
            return false;
        let content_01 = '';
        let sequence = 1;
        for (let i = 0; i < result.length; i++) {
            let linesid = result[i].linesId;
            sequence = i + 1;
            content_01 += '<tr _mash_id="' + linesid + '">';
            content_01 += '<td style="text-align:center;">' + sequence + '</td>';
            content_01 += '<td>' + formatNullData(result[i].poNo) + '</td>';
            content_01 += '<td>' + formatNullData(result[i].poBillTypeName) + '</td>';      // 合同类型
            content_01 += '<td>' + formatNullData(result[i].signedDate) + '</td>';          // 
            content_01 += '<td>' + formatNullData(result[i].orderArrivalDate) + '</td>';    // 
            content_01 += '<td>' + formatNullData(result[i].supplierName) + '</td>';        // 供应商名称
            content_01 += '<td>' + formatNullData(result[i].purchasedByName) + '</td>';     // 采购担当
            content_01 += '</tr>';
            $('#tabPoListData tbody').append(content_01);
            content_01 = '';
        }
        setOneTableRowColor("tabPoListData");
    }
    ImportPo() {
        let _this = this;
        parent.showModal(1340, 630, '引入采购订单', parent.basePath + '/purchase/po/for_stock_in/choice.html', null, ($dialog) => {
            let _exist = $.inArray($dialog, parent.arrDialog);
            if (_exist >= 0) {
                parent.arrDialog.splice($.inArray($dialog, parent.arrDialog), 1);
            }
            // 做选择设置
            if (parent.choice_success) {
                let PoHeaderIdList = [];
                let PoLinesIdList = [];
                for (let key in parent.arrChoice[0][0]) {
                    PoHeaderIdList.push(parseInt(key));
                }
                for (let key in parent.arrChoice[0][1]) {
                    let arrLinesId = key.split("/");
                    for (let i = 0; i < arrLinesId.length; i++) {
                        PoLinesIdList.push(arrLinesId[i]);
                    }
                }

                // 根据所选择的订单，形成入库明细
                let _params = {};
                _params['HeaderId'] = parseInt($('#HeaderId').val());
                _params['PoHeaderIdList'] = PoHeaderIdList;
                _params['PoLinesIdList'] = PoLinesIdList;
                _params['SelectAllFlag'] = parseInt(parent.arrChoice[0].SelectAllFlag);
                _params['StyleNoFilterVal'] = parent.arrChoice[0].StyleNoFilterValue;
                _params['MaterialCodeFilterVal'] = parent.arrChoice[0].MaterialNoFilterValue;
                _params['MaterialNameFilterVal'] = parent.arrChoice[0].MaterialNameFilterValue;
                _params['MaterialColourNameFilterVal'] = parent.arrChoice[0].MaterialColourNameFilterValue;
                _params['SupplierNameFilterVal'] = parent.arrChoice[0].SupplierNameFilterValue;
                _params['Limit02'] = parseInt($("#page-size_02").val());
                _params['Limit03'] = parseInt($("#page-size_03").val());
                _params['UserId'] = parseInt($("#UserId").val());
                $.ajax({
                    type: "POST",
                    url: parent.basePath + "/inventory/stock_in/lines/poheader/insert.html",
                    timeout: 60 * 1000,
                    data: JSON.stringify(_params),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    beforeSend: function () {
                    }
                }).done((data) => {
                    // 刷新明细记录
                    _this.BuildDataTable(data.LinesPoHeaderList);
                    _InstancePageLinesPoLines.BuildDataTable(data.LinesPoLinesList);
                    _InstancePageLines.BuildDataTable(data.LinesList);

                    ShowSuccessMessagePanel("引入采购订单成功。");
                }).fail((data) => {
                    ajaxError(data, 1);
                }).always(( ) => {
                });
            }
            // 清空数组
            parent.arrChoice.splice(0, parent.arrChoice.length);
            parent.choice_success = false;
        });
    }
}

class MyPageLinesPoLines extends BaseEditSlave {
    constructor() {
        super('', '', '');
        this.orderby = "";
        $("abbr.page_indicator_block,#wrapper__navbar_02").attr("_msh_page", 1);
    }
    SetPageSize02() {
        $.cookie("stock_in_po_lines_pagesize", $("#page-size_02").val());
        this.FetchLinesForPage(1);
    }
    // 获取明细表分页信息
    GetFilterValue(pageIndex) {
        if (pageIndex !== 0) {
            $("abbr.page_indicator_block,#wrapper__navbar_02").attr("_msh_page", pageIndex);
        }

        let item = {};
        item['HeaderId'] = parseInt(parent.$("#HeaderId").val());
        item['StyleNoFilterVal'] = formatNullInputValue($.trim($("#StyleNoFilterValue_02").val()));
        item['MaterialNameFilterVal'] = formatNullInputValue($.trim($("#MaterialNameFilterValue_02").val()));
        item['MaterialColourNameFilterVal'] = formatNullInputValue($.trim($("#MaterialColourNameFilterValue_02").val()));
        item['MaterialColourCodeFilterVal'] = formatNullInputValue($.trim($("#MaterialColourCodeFilterValue_02").val()));
        item['SpecificationFilterVal'] = formatNullInputValue($.trim($("#SpecificationFilterValue_02").val()));
        item['Limit'] = parseInt($("#page-size_02").val());       // limit;
        item['PageIndex'] = parseInt($("abbr.page_indicator_block,#wrapper__navbar_02").attr("_msh_page"));
        item['OrderBy'] = this.orderby;
        return JSON.stringify(item);
    }
    FetchAll() {
        $("#StyleNoFilterValue_02").val("");
        $("#MaterialNameFilterValue_02").val("");
        $("#MaterialColourCodeFilterValue_02").val("");
        $("#MaterialColourNameFilterValue_02").val("");
        $("#SpecificationFilterValue_02").val("");
        this.FetchLinesForPage(1);
    }
    // 取得引入的订单明细分页信息
    FetchLinesForPage(pageIndex) {
        let _this = this;
        $.ajax({
            type: "POST",
            url: parent.basePath + "/inventory/stock_in/lines/polines/FetchLinesForPage.html",
            timeout: 60 * 1000,
            data: _this.GetFilterValue(pageIndex),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function () {
                $("#loading__indicator_02 i").addClass("fa-spin");
                $("#loading__indicator_02").show();
            }
        }).done((data) => {
            _this.BuildDataTable(data);
        }).fail((data) => {
            ajaxError(data, 1);
        }).always(() => {
            $("#loading__indicator_02 i").removeClass("fa-spin");
            $("#loading__indicator_02").hide();
        });
    }
    // 构建明细数据列表
    BuildDataTable(result) {
        $('#tabData21 tbody').empty();
        $('#tabData22 tbody').empty();

        if (result.Success === false) {
            return;
        }
        // 设置翻页控件
        if (result.TotalPages > 0) {  //总页数
            $("#wrapper__navbar_02").data("swPagination").options.max_page = result.TotalPages;
        } else {
            $("#wrapper__navbar_02").data("swPagination").options.max_page = 1;
        }
        if (result.PageIndex > 0) { //当前页数
            $("#wrapper__navbar_02").data("swPagination").options.current_page = result.PageIndex;
            $("#wrapper__navbar_02").data("swPagination").setPage(result.PageIndex);
        } else {
            $("#wrapper__navbar_02").data("swPagination").options.current_page = 1; //当前页数
            $("#wrapper__navbar_02").data("swPagination").setPage(1);
        }

        // 得到数据列表
        result = result.DataList;
        if (result === null) {
            return false;
        }
        let content_01 = '';
        let content_02 = '';
        for (let i = 0; i < result.length; i++) {
            content_01 += '<tr _mash_id="' + result[i].linesId + '">';
            content_01 += '<td>' + formatNullData(result[i].poNo) + '</td>';
            content_01 += '<td style="text-overflow:ellipsis;" title="' + formatNullData(result[i].styleNo) + '">' + formatNullData(result[i].styleNo) + '</td>';
            content_01 += '<td>' + formatNullData(result[i].materialCode) + '</td>';
            content_01 += '<td>' + formatNullData(result[i].materialName) + '</td>';
            content_01 += '</tr>';

            content_02 += '<tr>';
            content_02 += '<td>' + formatNullData(result[i].materialColourNumber) + '</td>';                 // 色号
            content_02 += '<td>' + formatNullData(result[i].materialColourName) + '</td>';                   // 色名
            content_02 += '<td>' + formatNullData(result[i].specification) + '</td>';                        // 规格
            content_02 += '<td style="text-align:center;">' + formatNullData(result[i].uomName) + '</td>';   // 单位
            content_02 += '<td>' + formatNullData(result[i].poQuantity) + '</td>';                           // 订单数量
            content_02 += '<td>' + formatNullData(result[i].arrivedQuantity) + '</td>';                      // 已到数量
            content_02 += '<td>' + formatNullData(result[i].shouldBeQuantity) + '</td>';                     // 应到数
            content_02 += '<td>' + formatNullData(result[i].receivedQuantity) + '</td>';                     // 到货数
            content_02 += '<td style="border-right:none;">' + result[i].stockInQuantity + '</td>';           // 实到数量(入库数=结算对账数)
            content_02 += '</tr>';

            $("#tabData21 tbody").append(content_01);
            $("#tabData22 tbody").append(content_02);
            content_01 = '';
            content_02 = '';
        }
        setTwoTableRowColor("tabData21", "tabData22");
        $(window).resize();               // 防止因为出现滚动条而造成画面显示问题
    }
    ScrollTo() {
        $('#divH22').scrollLeft($('#divD22').scrollLeft());
        $('#divD21').scrollTop($('#divD22').scrollTop());
    }
    SortTable(order_by) {
        this.orderby = order_by;
        this.FetchLinesForPage(1);
    }
}

class MyPageLines extends BaseEditSlave {
    constructor() {
        super('', '', '');
        this.orderby = "";
        this.selectedItemList = [];
    }
    SetPageSize03() {
        $.cookie("stock_in_lines_pagesize", $("#page-size_03").val());
        this.FetchLinesForPage(1);
    }
    // 获取明细表分页信息
    GetFilterValue(pageIndex) {
        if (pageIndex !== 0) {
            $("abbr.page_indicator_block,#wrapper__navbar_03").attr("_msh_page", pageIndex);
        }

        let item = {};
        item['HeaderId'] = parseInt($.trim($("#HeaderId").val()));
        item['MaterialCodeFilterVal'] = formatNullInputValue($.trim($("#MaterialNoFilterValue_03").val()));
        item['MaterialNameFilterVal'] = formatNullInputValue($.trim($("#MaterialNameFilterValue_03").val()));
        item['MaterialColourNameFilterVal'] = formatNullInputValue($.trim($("#MaterialColourNameFilterValue_03").val()));
        item['SpecificationFilterVal'] = formatNullInputValue($.trim($("#SpecificationFilterValue_03").val()));
        item['Limit'] = parseInt($("#page-size_03").val());       // limit;
        item['PageIndex'] = parseInt($("abbr.page_indicator_block,#wrapper__navbar_03").attr("_msh_page"));
        item['OrderBy'] = this.orderby;
        return JSON.stringify(item);
    }
    FetchAll() {
        $("#MaterialNameFilterValue_03").val("");
        $("#MaterialColourCodeFilterValue_03").val("");
        $("#MaterialColourNameFilterValue_03").val("");
        $("#SpecificationFilterValue_03").val("");
        this.FetchLinesForPage(1);
    }
    // 取得入库单明细分页信息
    FetchLinesForPage(pageIndex) {
        let _this = this;
        $.ajax({
            type: "POST",
            url: parent.basePath + "/inventory/stock_in/lines/fetchForPage.html",
            timeout: 60 * 1000,
            data: _this.GetFilterValue(pageIndex),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function () {
                $("#loading__indicator_03 i").addClass("fa-spin");
                $("#loading__indicator_03").show();
            }
        }).done((data) => {
            _this.BuildDataTable(data);
        }).fail((data) => {
            ajaxError(data, 1);
        }).always(() => {
            $("#loading__indicator_03 i").removeClass("fa-spin");
            $("#loading__indicator_03").hide();
        });
    }
    // 构建明细数据列表
    BuildDataTable(result) {
        $('#tabData31 tbody').empty();
        $('#tabData32 tbody').empty();

        if (result.Success === false) {
            return;
        }
        // 设置翻页控件
        if (result.TotalPages > 0) {  //总页数
            $("#wrapper__navbar_03").data("swPagination").options.max_page = result.TotalPages;
        } else {
            $("#wrapper__navbar_03").data("swPagination").options.max_page = 1;
        }
        if (result.PageIndex > 0) { //当前页数
            $("#wrapper__navbar_03").data("swPagination").options.current_page = result.PageIndex;
            $("#wrapper__navbar_03").data("swPagination").setPage(result.PageIndex);
        } else {
            $("#wrapper__navbar_03").data("swPagination").options.current_page = 1; //当前页数
            $("#wrapper__navbar_03").data("swPagination").setPage(1);
        }

        // 得到数据列表
        result = result.DataList;
        if (result === null) {
            return false;
        }
        let content_01 = '';
        let content_02 = '';
        this.numCheckbox = result.length;
        for (let i = 0; i < result.length; i++) {
            let _trcss = '';
            if (result[i].payedFlag) {
                _trcss = 'class="row__quoted"';
            }
            content_01 += '<tr ' + _trcss + ' _mash_id="' + result[i].linesId + '">';
            if (result[i].payedFlag) {  // 如果已经对账，则不能删除
                content_01 += '<td></td>';
                content_01 += '<td></td>';
            } else {
                content_01 += '<td style="padding-left:5px;"><label class="btn" for="R-' + result[i].linesId + '"><input id="R-' + result[i].linesId + '" name="_check_row" type="checkbox" onclick="_InstancePageLines.DoCheckRow($(this),\'_check_row\',$(\'#checkall\'));" value="' + result[i].linesId + '"/><i></i><span></span></label></td>';
                content_01 += '<td class="column__action"><span title="删除" class="trash" onclick="_InstancePageLines.DoDelete($(this));"><i class="fa-all fa-trash-o fa-1"></i></span></td>';
            }
            content_01 += '<td _msh_poid="' + result[i].poHeaderId + '">' + formatNullData(result[i].poNo) + '</td>';
            content_01 += '<td style="text-overflow:ellipsis;" title="' + formatNullData(result[i].styleNo) + '">' + formatNullData(result[i].styleNo) + '</td>';
            content_01 += '<td>' + formatNullData(result[i].materialCode) + '</td>';
            content_01 += '<td>' + formatNullData(result[i].materialName) + '</td>';
            content_01 += '</tr>';

            content_02 += '<tr ' + _trcss + ' _mash_id="' + result[i].linesId + '" _material_id="' + result[i].materialId + '">';
            content_02 += '<td>' + formatNullData(result[i].materialColourNumber) + '</td>';                 // 色号
            content_02 += '<td>' + formatNullData(result[i].materialColourName) + '</td>';                   // 色名
            if (result[i].payedFlag) {  // 如果已经对账，则不能修改
                content_02 += '<td _spec="' + formatNullData(result[i].specification) + '">' + formatNullData(result[i].specification) + '</td>';          // 实到规格
                content_02 += '<td style="text-align:center;">' + formatNullData(result[i].uomName) + '</td>';   // 单位
                content_02 += '<td>' + formatNullData(result[i].coefficient) + '</td>';      // 系数
                content_02 += '<td>' + formatNullData(result[i].receivedQuantity) + '</td>'; // 到货数
                content_02 += '<td>' + result[i].shortRuleQuantity + '</td>';                // 短尺数量
                content_02 += '<td>' + result[i].stockInQuantity + '</td>';                  // 实到数量(入库数=结算对账数)
                content_02 += '<td>' + result[i].poQuantity + '</td>';                       // 订单数
                content_02 += '<td>' + result[i].maxPoQuantity + '</td>';                    // 最大订单数（含到货允许）
                content_02 += '<td style="border-right:none;">' + formatNullData(result[i].description) + '</td>';  // 备注
            } else {
                content_02 += '<td class="edited-cell" _spec="' + formatNullData(result[i].specification) + '">' + formatNullData(result[i].specification) + '</td>';          // 实到规格
                content_02 += '<td style="text-align:center;">' + formatNullData(result[i].uomName) + '</td>';   // 单位
                content_02 += '<td class="edited-cell">' + formatNullData(result[i].coefficient) + '</td>';      // 系数
                content_02 += '<td class="edited-cell">' + formatNullData(result[i].receivedQuantity) + '</td>'; // 到货数
                content_02 += '<td class="edited-cell">' + result[i].shortRuleQuantity + '</td>';                // 短尺数量
                content_02 += '<td class="edited-cell">' + result[i].stockInQuantity + '</td>';                  // 实到数量(入库数=结算对账数)
                content_02 += '<td>' + result[i].poQuantity + '</td>';                       // 订单数
                content_02 += '<td>' + result[i].maxPoQuantity + '</td>';                    // 最大订单数（含到货允许）
                content_02 += '<td class="edited-cell" style="border-right:none;">' + formatNullData(result[i].description) + '</td>';  // 备注
            }
            content_02 += '</tr>';

            $("#tabData31 tbody").append(content_01);
            $("#tabData32 tbody").append(content_02);
            content_01 = '';
            content_02 = '';
        }
        setTwoTableRowColor("tabData31", "tabData32");
        $(window).resize();               // 防止因为出现滚动条而造成画面显示问题
        this.ResetSelectRowStatus();

        let cell_id = "_cell__field";
        let cell_name = "__cell__field";
        let _this = this;
        $('#tabData32 tbody tr').find("td.edited-cell").click(function () {
            switch ($(this).index()) {
                default:
                    OnCellClickEvent($(this), cell_id, cell_name, 0);
                    break;
            }
        });
    }
    // 得到要保存的数据
    GetLinesData() {
        let itemList = [];
        // 得到修改过数据
        $('#tabData32 tbody').find("tr").each(function (index) {
            let $tr2 = $(this);
            let $tr1 = $('#tabData31 tbody').find("tr").eq(index);
            if ($tr2.find("td.dirty").length || $tr1.find("td.dirty").length) {
                let item = {};
                item['headerId'] = $("#HeaderId").val();
                item['linesId'] = $(this).attr('_mash_id');
                item['materialId'] = $(this).attr('_material_id');
                item['poHeaderId'] = formatNullInputValue($.trim($tr1.find('td').eq(2).attr("_msh_poid")));          // 采购订单标识                
                item['materialColourName'] = formatNullInputValue($.trim($(this).find('td').eq(1).text()));          // 材料色
                //item['actualSpecification'] = formatNullInputValue($.trim($(this).find('td').eq(2).text()));         // 实到规格
                item['specification'] = formatNullInputValue($.trim($(this).find('td').eq(2).text()));               // 采购规格
                item['coefficient'] = formatNullInputValue($.trim($(this).find('td').eq(4).text()));                 // 系数
                item['receivedQuantity'] = formatNullInputValue($.trim($(this).find('td').eq(5).text()));            // 实到数量
                item['shortRuleQuantity'] = formatNullInputValue($.trim($(this).find('td').eq(6).text()));           // 短尺数量
                item['stockInQuantity'] = formatNullInputValue($.trim($(this).find('td').eq(7).text()));             // 入库数量
                item['description'] = formatNullInputValue($.trim($(this).find('td').eq(10).text()));                // 备注
                item['updatedBy'] = $("#UserId").val();

                itemList.push(item);
            }
        });

        let _params = {};
        _params['ItemList'] = itemList;
        _params['Limit02'] = parseInt($("#page-size_02").val());
        _params['PageIndex02'] = parseInt($("abbr.page_indicator_block,#wrapper_navbar_02").attr("_msh_page"));
        _params['Limit03'] = parseInt($("#page-size_03").val());
        _params['PageIndex03'] = parseInt($("abbr.page_indicator_block,#wrapper_navbar_03").attr("_msh_page"));

        return JSON.stringify(_params);
    }
    SaveLines() {
        if ($('#tabData32 tbody tr td.dirty').length === 0) {
            ShowSuccessMessagePanel("保存成功。");
            return false;
        }
        //step 1、进行页面验证，失败则返回
        let success_01 = CheckGridInput();
        if (!success_01)
            return;

        super.SaveLines("/inventory/stock_in/lines/update.html", (data, _this) => {
            _this.BuildDataTable(data.LinesList);
            _InstancePageLinesPoLines.BuildDataTable(data.LinesPoLinesList);
            $("#checkall").prop("checked", false);
            ShowSuccessMessagePanel("保存成功。");
        });
    }
    // 批量选择的数据
    GetCheckedLinesData() {
        let _result = [];
        if ($("input[type='checkbox'][name='_check_row']:checked").length > 0) {
            $("input[type='checkbox'][name='_check_row']:checked").each(function () {
                let $tr = $(this).parent().parent().parent();
                let item = {};
                item['headerId'] = parseInt($("#HeaderId").val());
                item['linesId'] = $(this).val();
                item['deletedBy'] = $("#UserId").val();
                _result.push(item);
            });
        }
        return JSON.stringify(_result);
    }
    // 批量删除
    BatchDeleteLines() {
        if ($("input[type='checkbox'][name='_check_row']:checked").length <= 0) {
            ShowErrorMessagePanel("请选择要删除的数据。");
            return false;
        }

        let params = {};
        params['HeaderId'] = parseInt($("#HeaderId").val());
        params['DeletedBy'] = parseInt($("#UserId").val());
        params['CurrentUserId'] = parseInt($("#UserId").val());      // 当前操作者，用于过滤供应商分组
        params['Limit02'] = parseInt($("#page-size_02").val());
        params['PageIndex02'] = parseInt($("abbr.page_indicator_block,#wrapper__navbar_02").attr("_msh_page"));
        params['Limit03'] = parseInt($("#page-size_03").val());
        params['PageIndex03'] = parseInt($("abbr.page_indicator_block,#wrapper__navbar_03").attr("_msh_page"));

        let choiced_data = [];
        if ($("input[type='checkbox'][name='_check_row']:checked").length > 0) {
            $("input[type='checkbox'][name='_check_row']:checked").each(function () {
                let item = {};
                item['headerId'] = $("#HeaderId").val();
                item['linesId'] = $(this).parent().parent().parent().attr("_mash_id");
                item['deletedBy'] = $.trim($("#UserId").val());
                choiced_data.push(item);
            });
        }
        params['DeletedLinesList'] = choiced_data;

        // * BatchDeleteLines（url,(data, _this) => {});
        super.DoAjax(params, "/inventory/stock_in/lines/batch_delete.html", (data, _this) => {
            _this.BuildDataTable(data.LinesList);
            _InstancePageLinesPoHeader.BuildDataTable(data.LinesPoHeaderList);
            _InstancePageLinesPoLines.BuildDataTable(data.LinesPoLinesList);
            $("#checkAll").prop("checked", false);
            ShowSuccessMessagePanel("批量删除完成。");
        });
    }
    // 删除
    DoDelete($self) {
        let params = {};
        params['HeaderId'] = parseInt($("#HeaderId").val());
        params['LinesId'] = $self.parent().parent().attr("_mash_id");
        params['DeletedBy'] = parseInt($("#UserId").val());
        params['Limit02'] = parseInt($("#page-size_02").val());
        params['PageIndex02'] = parseInt($("abbr.page_indicator_block,#wrapper__navbar_02").attr("_msh_page"));
        params['Limit03'] = parseInt($("#page-size_03").val());
        params['PageIndex03'] = parseInt($("abbr.page_indicator_block,#wrapper__navbar_03").attr("_msh_page"));

        super.DeleteLines(params, "/inventory/stock_in/lines/delete.html", function (data, _this) {
            _this.BuildDataTable(data.LinesList);
            _InstancePageLinesPoHeader.BuildDataTable(data.LinesPoHeaderList);
            _InstancePageLinesPoLines.BuildDataTable(data.LinesPoLinesList);
            $("#checkAll").prop("checked", false);
            ShowSuccessMessagePanel("删除成功。");
        });
    }
    SetRowStatus($self) {
        let key = $self.val();
        let $row = $self.parent().parent().parent();
        let rowIndex = $row.index();
        if ($self.is(":checked") === true) {
            $row.addClass("row__selected");
            $('#tabData32 tbody tr:eq(' + rowIndex + ')').addClass("row__selected");
            // 设置 编辑、删除按钮失效
            $row.children('td').eq(1).children('span').eq(0).attr("onclick", "");
            let item = {};
            // 为翻页选择做准备
            item["linesId"] = key;
            this.selectedItemList[key] = item;
        } else {
            $row.removeClass("row__selected");
            $('#tabData32 tbody tr:eq(' + rowIndex + ')').removeClass("row__selected");
            // 设置删除按钮有效
            var _event_delete_onclick = "_InstancePageLines.DoDelete($(this))";
            $row.children('td').eq(1).children('span').eq(0).attr("onclick", _event_delete_onclick);
            delete this.selectedItemList[key];
        }
    }
    // 每次翻页都恢复选定结果
    ResetSelectRowStatus() {
        let _this = this;
        $("#tabData31 tbody").find("tr").each(function (index) {
            let key = $(this).attr("_mash_id");
            if (_this.selectedItemList[key] !== undefined) {
                $(this).children("td").eq(0).children("label").eq(0).children("input[type='checkbox'][name='_check_row']").eq(0).prop('checked', true);
                $(this).addClass("row__selected");
                $('#tabData32 tbody tr:eq(' + index + ')').addClass("row__selected");
            }
        });
        // 设置选择全部的状态
        let n = $("input[type='checkbox'][name='_check_row']:checked").length;
        if (n < $("#tabData31 tbody").find("tr").length || n === 0) {
            $("#checkall").prop("checked", false);
        } else {
            $("#checkall").prop("checked", true);
        }
    }
    ScrollTo() {
        $('#divH32').scrollLeft($('#divD32').scrollLeft());
        $('#divD31').scrollTop($('#divD32').scrollTop());
    }
    SortTable(order_by) {
        this.orderby = order_by;
        this.FetchLinesForPage(1);
    }
}

var _InstancePageHeader = null;
var _InstancePageLines = null;
var _InstancePageLinesPoHeader = null;
var _InstancePageLinesPoLines = null;

//-----------------------------------------------------------------------------
// 页面初始化
//-----------------------------------------------------------------------------
function onPageReady() {
    let _pageStatus = parseInt($("#Action").val());
    let _dataId = $("#HeaderId").val();

    let stock_in_list_result = $.cookie("stock_in_list_result") === undefined ? "" : $.cookie("stock_in_list_result");
    let _pageListData = [];
    if (stock_in_list_result !== "") {
        _pageListData = stock_in_list_result.split(',');
        $("#rec_total_rows").text(_pageListData.length);
        $("#rec_cur_row").text($.inArray(_dataId, _pageListData) + 1);

        if (_pageListData.length > 0) {
            let index = $.inArray(_dataId, _pageListData);
            if (index === 0) {
                $("#ButPrev").attr("disabled", "disabled");
            } else {
                $("#ButNext").removeAttr("disabled");
            }
            if (index === (_pageListData.length - 1)) {
                $("#ButNext").attr("disabled", "disabled");
            } else {
                $("#ButPrev").removeAttr("disabled");
            }
        }
    } else {
        $("#rec_total_rows").text("1");
        $("#rec_cur_row").text("1");
    }
    _InstancePageHeader = new MyPageHeader(_dataId, 0, 0, _pageStatus, _pageListData,
            "/inventory/stock_in/list.html",
            "/inventory/stock_in/header/fetchByKey.html",
            "/inventory/stock_in/header/save.html",
            "/inventory/stock_in/export.html",
            "/inventory/stock_in/print.html");
    _InstancePageLines = new MyPageLines();
    _InstancePageLinesPoHeader = new MyPageLinesPoHeader();
    _InstancePageLinesPoLines = new MyPageLinesPoLines();

    window.laydate.render({
        elem: '#ArrivalDate',
        theme: '#393D49',
        trigger: 'click'
    });
    window.laydate.render({
        elem: '#InspectedDate',
        theme: '#393D49',
        trigger: 'click'
    });
    window.laydate.render({
        elem: '#StockInDate',
        theme: '#393D49',
        trigger: 'click'
    });

    $("#loading__indicator_02").hide();
    $("#loading__indicator_03").hide();

    $("#tabPanelHeader").wxTabs({tabContent: "tabPanelContent"});

    // 设置引入的订单明细分页控制
    $("#wrapper__navbar_02").swPagination({
        link_string: '/?page={page_number}',
        max_page: null,
        paged: function (page) {
            $("abbr.page_indicator_block,#wrapper__navbar_02").attr("_msh_page", page);
            _InstancePageLinesPoLines.FetchLinesForPage(page);
        }
    });
    // 设置明细分页控制
    $("#wrapper__navbar_03").swPagination({
        link_string: '/?page={page_number}',
        max_page: null,
        paged: function (page) {
            $("abbr.page_indicator_block,#wrapper__navbar_03").attr("_msh_page", page);
            _InstancePageLines.FetchLinesForPage(page);
        }
    });
    // 设置订单明细表格排序字段
    $("#tabHeader21").wxTableSorter({
        sortList: [[1, 2], [2, 2], [3, 2]], // 第一个表示列的序号，第二个表示排序种类
        headers: {1: {sorter: false}, 2: {sorter: false}, 3: {sorter: false}},
        columnList: [[1, "POL.StyleNo"],
            [2, "M.MaterialCode"],
            [3, "M.MaterialName"]],
        detailList: $("#tabData21"),
        sort: function (orderBy, index) {
            switch (index) {
                // 按款号
                case 0:
                    orderBy = orderBy + ", COALESCE(POL.ProductColourName,''), M.MaterialCode, COALESCE(POL.MaterialColourName,''), COALESCE(POL.Specification,''), POL.UpdatedDate DESC";
                    break;
                    // 按料号
                case 1:
                    orderBy = orderBy + ", POL.StyleNo, COALESCE(POL.ProductColourName,''), COALESCE(POL.MaterialColourName,''), COALESCE(POL.Specification,''), POL.UpdatedDate DESC";
                    break;
                    // 按料名
                case 2:
                    orderBy = orderBy + ", POL.StyleNo, COALESCE(POL.ProductColourName,''), COALESCE(POL.MaterialColourName,''), COALESCE(POL.Specification,''), POL.UpdatedDate DESC";
                    break;
            }
            _InstancePageLinesPoLines.SortTable(orderBy);
        }
    });
    $("#tabHeader22").wxTableSorter({
        sortList: [[1, 2]], // 第一个表示列的序号，第二个表示排序种类
        headers: {1: {sorter: false}},
        columnList: [[1, "POL.MaterialColourName"]],
        detailList: $("#tabData22"),
        sort: function (orderBy, index) {
            switch (index) {
                case 0:
                    orderBy = orderBy + ", POL.StyleNo, COALESCE(POL.ProductColourName,''), M.MaterialCode, COALESCE(POL.Specification,''), POL.UpdatedDate DESC";
                    break;
            }
            _InstancePageLinesPoLines.SortTable(orderBy);
        }
    });
    SetSearchWnd();
    _InstancePageHeader.OnPageLoad();
}

// 画面大小或者位置移动
function onPageResize() {
    let w = $(window).width();

    let wLeftList_2 = 740;
    $("#divH22").css({width: w - 16 - wLeftList_2});
    $("#divD22").css({left: -1, width: w - wLeftList_2 - 15});

    let wLeftList_3 = 667; // 订单明细左边列表固定宽度
    $("#divH32").css({width: w - 16 - wLeftList_3});
    $("#divD32").css({left: -1, width: w - wLeftList_3 - 15});
}

function SetSearchWnd() {
    $("div.search").unbind('keyup');

    let clazz = 'search--active';
    // 设置引入订单表头的搜索
    let $search_02 = $('#search_02');
    // 搜索按钮
    $('#search_btn_02').on('click', function (event) {
        $search_02.addClass(clazz);
        $search_02.on(window.transitionProp, function (event) {
            $search_02.find('input').first().focus();
        });
    });
    // 搜索窗口关闭
    $('#search__form_butclose_02').on('click', function (event) {
        $search_02.removeClass(clazz);
    });
    // 搜索框回车直接进行搜索
    $("#search_02").bind('keyup', function (e) {
        let key = e.keyCode;
        if (key === 13) {
            $("#but_filter_02").click();
        }
    });

    // 设置引入订单明细的搜索
    let $search_03 = $('#search_03');
    // 搜索按钮
    $('#search_btn_03').on('click', function (event) {
        $search_03.addClass(clazz);
        $search_03.on(window.transitionProp, function (event) {
            $search_03.find('input').first().focus();
        });
    });
    // 搜索窗口关闭
    $('#search__form_butclose_03').on('click', function (event) {
        $search_03.removeClass(clazz);
    });
    // 搜索框回车直接进行搜索
    $("#search_03").bind('keyup', function (e) {
        let key = e.keyCode;
        if (key === 13) {
            $("#but_filter_03").click();
        }
    });
}

//-----------------------------------------------------------------------------
// 验证函数
//-----------------------------------------------------------------------------
$.validator.setDefaults({
    ignore: 'hidden, [reaonly=readonly]'
});
$.validator.addMethod("valueNotEquals", function (value, element, arg) {
    return arg !== value;
}, "Value must not equal arg.");

$(function () {
    $("#form_data").validate({
        // Step 1：设置验证规则和错误消息
        rules: {
            _BillNo: "required",
            _ArrivalDate: {
                dateISO: true,
                required: true
            },
            _StockInDate: {
                dateISO: true,
                required: true
            },
            _SupplierName: "required",
            _ReasonId: {
                valueNotEquals: "-1",
                required: true
            }
        },
        messages: {
            _BillNo: "请填写入库单号。",
            _ArrivalDate: {
                dateISO: "请填写正确的日期。",
                required: "请填写到货日期。"
            },
            _StockInDate: {
                dateISO: "请填写正确的日期。",
                required: "请填写入库日期。"
            },
            _SupplierName: "请填写供应商。",
            _ReasonId: {
                valueNotEquals: "请选择入库类型。",
                required: "请选择入库类型。"
            }

        },
        // Step 2：设置验证触发事件
        onclick: false,
        onfocusout: false,
        onfocusin: false,
        onkeyup: false,
        onkeydown: false,
        focusInvalid: false,
        // Step 3：设置错误信息提示
        showErrors: window.showErrors  //使用自定义的错误显示方法
    });
});
// 验证输入
function CheckGridInput() {
    $('#tabData32 tbody').find("tr").each(function (index) {
        let $tr2 = $('#tabData32 tbody').find("tr").eq(index);
        let _quantity04 = $.trim($tr2.find('td').eq(4).text()) === '' ? 0 : $.trim($tr2.find('td').eq(4).text());   // 转换系数
        let _quantity05 = $.trim($tr2.find('td').eq(5).text()) === '' ? 0 : $.trim($tr2.find('td').eq(5).text());   // 到货数
        let _quantity06 = $.trim($tr2.find('td').eq(7).text()) === '' ? 0 : $.trim($tr2.find('td').eq(6).text());   // 短尺数
        let _quantity07 = $.trim($tr2.find('td').eq(8).text()) === '' ? 0 : $.trim($tr2.find('td').eq(7).text());   // 结算数

        if (_quantity04 !== 0) {
            if (!isNumber(_quantity04)) {
                GridCheckErrHandle($tr2, 4, '请输入正确的数字。');
            } else {
                GridCheckSuccessHandle($tr2, 4);
            }
        }
        if (_quantity05 !== 0) {
            if (!isNumber(_quantity05)) {
                GridCheckErrHandle($tr2, 5, '请输入正确的数字。');
            } else {
                GridCheckSuccessHandle($tr2, 5);
            }
        }
        if (_quantity06 !== 0) {
            if (!isNumber(_quantity06)) {
                GridCheckErrHandle($tr2, 6, '请输入正确的数字。');
            } else {
                GridCheckSuccessHandle($tr2, 6);
            }
        }
        if (_quantity07 !== 0) {
            if (!isNumber(_quantity07)) {
                GridCheckErrHandle($tr2, 7, '请输入正确的数字。');
            } else {
                GridCheckSuccessHandle($tr2, 7);
            }
        }
    });
    if ($('#tabData31 tbody').find('td.error').length > 0 || $('#tabData32 tbody').find('td.error').length > 0) {
        ShowErrorMessagePanel('对不起，填写的数据有错误。');
        return false;
    } else {
        return true;
    }
}
function GridCheckErrHandle($row, index, errMsg) {
    $row.find('td').eq(index).addClass("error");
    $row.find('td').eq(index).attr('title', errMsg);
}
function GridCheckSuccessHandle($row, index) {
    $row.find('td').eq(index).removeClass("error");
    $row.find('td').eq(index).attr('title', '');
}